﻿using System;
using UnityEditor;
using UnityEngine;

namespace UPA
{
    public class CLITools
    {
        public static void Execute()
        {
            string[] args = Environment.GetCommandLineArgs();
            string actionGroupPath = string.Empty;
            string settingName = string.Empty;
            foreach (string arg in args)
            {
                if (arg.StartsWith("-actionGroup", StringComparison.OrdinalIgnoreCase))
                {
                    var array = arg.Split('=');
                    if (array.Length >= 2)
                    {
                        actionGroupPath = array[1].Replace('\\', '/');
                    }
                }
                else if (arg.StartsWith("-settingName", StringComparison.OrdinalIgnoreCase))
                {
                    var array = arg.Split('=');
                    if (array.Length >= 2)
                    {
                        settingName = array[1];
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(actionGroupPath))
            {
                throw new Exception("未指定自动流程资源路径");
            }

            if (string.IsNullOrWhiteSpace(settingName))
            {
                throw new Exception("未指定使用的配置");
            }

            if (!actionGroupPath.EndsWith(".asset"))
            {
                actionGroupPath += ".asset";
            }

            var actionGroup = AssetDatabase.LoadAssetAtPath<ProcessActionGroup>(actionGroupPath);
            if (!actionGroup)
            {
                throw new Exception($"资源路径不存在:{actionGroupPath}");
            }

            var settingIndex = actionGroup.Settings.FindIndex(item =>
                item.Name.Equals(settingName, StringComparison.OrdinalIgnoreCase));
            if (settingIndex == -1)
            {
                throw new Exception($"未找到指定配置:{settingName}");
            }

            actionGroup.CurSelectSettingIndex = settingIndex;

            foreach (var unit in actionGroup.ActionUnits)
            {
                var action = unit.Action;
                try
                {
                    var result = action.Execute();
                    if (!result.Finished)
                    {
                        throw new Exception($"{action.Name}:{result.ErrorMessage}");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                    throw new Exception($"{action.Name}抛出异常,详细信息请查看日志");
                }
            }
        }
    }
}